package com.tozed.android.launcher.simpleui;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.android.internal.telephony.cat.ResultCode;
import com.tozed.android.launcher.LauncherApplication;
import com.tozed.android.launcher.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SearchView;
import android.widget.TextView;

public class AllAppScrollView extends ScrollView implements SearchView.OnQueryTextListener
{
	private static final String TAG = "AllAppScrollView";
	private static final int MAX_RECENT_TASKS = 21;
	private static final int RECENT_MAX_DISPLAY_ITEM = 8;
	private ArrayList<SimpleApplicationInfo> mAllApps = new ArrayList<SimpleApplicationInfo>();
	private AppsAdapter mAllAppsAdapter;
	private GridView mAllAppsGridView;
	private TextView mAllTextView;
	private int mCellHeight;
	private int mCellWidth;
	private Context mContext;
	private TextView mEmptyResultText;
	private Handler mHandler = null;
	private LauncherApplication mLauncherApp;
	private ArrayList<SimpleApplicationInfo> mRecentApps = new ArrayList<SimpleApplicationInfo>();
	private AppsAdapter mRecentAppsAdapter;
	private TextView mRecentTextView;
	private GridView mRecentlyUsedGridView;
	private View mSearchBg;
	private ArrayList<SimpleApplicationInfo> mSearchResultApps = new ArrayList<SimpleApplicationInfo>();
	private AppsAdapter mSearchResultAppsAdapter;
	private GridView mSearchResultGridView;
	private SearchView mSearchWidget;
	private int mTextColor;

	
	public AllAppScrollView(Context context){
		this(context, null, 0);
	}

	public AllAppScrollView(Context context, AttributeSet attrs){
		this(context, null, 0);
	}

	public AllAppScrollView(Context context, AttributeSet attrs, int defStyle){
		super(context, attrs, defStyle);

		init(context);
	}
	
	private void init(Context context){
		mContext = context;
		
	    mLauncherApp = LauncherApplication.getActiveInstance();
	    Resources res = context.getResources();
	    mCellWidth = res.getDimensionPixelSize(R.dimen.add_app_cell_width);
	    mCellHeight = res.getDimensionPixelSize(R.dimen.add_app_cell_height);
	    
	    mTextColor = res.getColor(R.color.simple_add_application);
	    
        setContentApps();
        mHandler = new Handler();
	}
	
	@Override
	protected void onFinishInflate()
	{
		super.onFinishInflate();
		
		loadRecentApps();
		
	    mRecentTextView = ((TextView)findViewById(R.id.recent_apps_text));
	    mRecentTextView.setTextColor(mTextColor);
	    mAllTextView = ((TextView)findViewById(R.id.all_apps_text));
	    mAllTextView.setTextColor(mTextColor);
	    mRecentlyUsedGridView = ((GridView)findViewById(R.id.recently_used));
	    
	    mRecentAppsAdapter = new AppsAdapter(mRecentApps);
	    mRecentAppsAdapter.setNotifyOnChange(false);
	    mRecentlyUsedGridView.setAdapter(mRecentAppsAdapter);
	    if ((mRecentApps != null) && (mRecentApps.size() == 0))
	      mRecentTextView.setVisibility(View.GONE);
	    
	    mAllAppsGridView = ((GridView)findViewById(R.id.all_grid));
	    mAllAppsAdapter = new AppsAdapter(mAllApps);
	    mAllAppsAdapter.setNotifyOnChange(false);
	    mAllAppsGridView.setAdapter(mAllAppsAdapter);
	    mSearchResultGridView = ((GridView)findViewById(R.id.all_result_app_grid));
	    mSearchResultGridView.setVisibility(View.GONE);
	    
	    updateLayoutHeight();
	    
	    mSearchBg = findViewById(R.id.search_bg);
	    mSearchWidget = ((SearchView)findViewById(R.id.search_app));
	    mSearchWidget.setOnCloseListener(new SearchCloseListener());
	    mSearchWidget.setOnQueryTextListener(this);
	    mSearchWidget.setOnTouchListener(new SearchTouchListener());
	    mSearchWidget.setOnQueryTextFocusChangeListener(new SearchQueryFocusListener());
	    mEmptyResultText = ((TextView)findViewById(R.id.search_no_result));
	    
	    setId(R.id.all_apps_scroll_view);
	}
	
	private void setContentApps()
	{
		mAllApps.clear();
		int otherAppsSize = SimpleLauncherModel.sOtherApps.size();
		int downLoadAppsSize = SimpleLauncherModel.sDownloadApps.size();
		
		for (int i = 0; i < otherAppsSize; i ++)
		{
			try{
				SimpleApplicationInfo app = SimpleLauncherModel.sOtherApps.get(i);
				mAllApps.add(app);
			} catch (IndexOutOfBoundsException e){
				Log.w(TAG, "setContentApps() the clearItems() in simplelunchermodel.java has been called ");
			}
		}
		
		for (int j = 0; j < downLoadAppsSize; j ++)
		{
			try{
				SimpleApplicationInfo app = SimpleLauncherModel.sDownloadApps.get(j);
				mAllApps.add(app);
			} catch (IndexOutOfBoundsException ex){
				Log.w(TAG, "setContentApps() the clearItems() in simplelunchermodel.java has been called ");
			}
		}
	}
	
	private void updateAllApps(SimpleApplicationInfo app, boolean removed)
	{
		if (removed){
			mAllApps.remove(app);
		}
		else{
			if (!mAllApps.contains(app))
				mAllApps.add(app);
		}
		
		updateAllAppsLayout();
	}

	private void updateAllAppsLayout()
	{
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mAllAppsGridView.getLayoutParams();
		lp.height = SimpleUtilities.getValidRows(mAllApps.size()) * mCellHeight;
		lp.width = (4 * mCellWidth);
	    mAllAppsGridView.setLayoutParams(lp);
	    
	    mAllAppsAdapter = new AppsAdapter(mAllApps);
	    mAllAppsAdapter.setNotifyOnChange(false);
	    mAllAppsGridView.setAdapter(mAllAppsAdapter);
	    
	    scrollTo(0, 0);
	}
	
	private void updateLayoutHeight()
	{
		LinearLayout.LayoutParams lpRecently = (LinearLayout.LayoutParams)mRecentlyUsedGridView.getLayoutParams();
		lpRecently.height = (SimpleUtilities.getValidRows(mRecentApps.size()) * mCellHeight);
		lpRecently.width = (4 * mCellWidth);
		mRecentlyUsedGridView.setLayoutParams(lpRecently);
		
		LinearLayout.LayoutParams lpAllApps = (LinearLayout.LayoutParams) mAllAppsGridView.getLayoutParams();
		lpAllApps.height = (SimpleUtilities.getValidRows(mAllApps.size()) * mCellHeight);
		lpAllApps.width = (4 * mCellWidth);
		mAllAppsGridView.setLayoutParams(lpAllApps);
		
		scrollTo(0, 0);
	}
	
	private void updateRecentLayout()
	{
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mRecentlyUsedGridView.getLayoutParams();
		int i = SimpleUtilities.getValidRows(this.mRecentApps.size());
		
		Log.i(TAG, "AllAppScrollView recentRows = " + i);
		
		lp.height = (i * mCellHeight);
		lp.width = (4 * mCellWidth);
		
		mRecentlyUsedGridView.setLayoutParams(lp);
		mRecentAppsAdapter = new AppsAdapter(mRecentApps);
		mRecentAppsAdapter.setNotifyOnChange(false);
		mRecentlyUsedGridView.setAdapter(mRecentAppsAdapter);
		
		if (mRecentApps.size() == 0){
			mRecentTextView.setVisibility(View.GONE);
		}else{
			if (mSearchResultGridView == null || mSearchResultGridView.getVisibility() == View.GONE)
				mRecentTextView.setVisibility(View.VISIBLE);
		}
		
		scrollTo(0, 0);
	}
	
	public CharSequence clearSearchWidget()
	{
		SearchView searchView = mSearchWidget;
		CharSequence queryResult = null;
		
		if (searchView != null){
			queryResult = mSearchWidget.getQuery();
			mSearchWidget.setIconified(true);
			mSearchWidget.setIconified(true);
		}
		
		return queryResult;
	}
	
	// 输入法事件
	public boolean dispatchKeyEventPreIme(KeyEvent keyEvent)
	{
		if ((keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK) 
		     && (keyEvent.getAction() == KeyEvent.ACTION_DOWN))
		{
			if (mSearchWidget.isIconified()){
				AddApplication addAppActivity = (AddApplication)mContext;
				addAppActivity.setResult(Activity.RESULT_CANCELED);
				addAppActivity.finish();
				return true;
			}
			
			mSearchWidget.setIconified(true);
			mSearchWidget.setIconified(true);
			return true;
		}
		
		return super.dispatchKeyEventPreIme(keyEvent);
	}
	
	public void loadRecentApps()
	{
		mRecentApps.clear();
		
	    PackageManager pm = mContext.getPackageManager();
	    List<RecentTaskInfo> recentTaskList = ((ActivityManager)mContext.getSystemService("activity"))
	    				.getRecentTasks(MAX_RECENT_TASKS, 2);
	    
	    int recentTaskSize = recentTaskList.size();
	    for (int i = 0; i < recentTaskSize; i++)
	    {
	        ActivityManager.RecentTaskInfo recentTaskInfo = (ActivityManager.RecentTaskInfo)recentTaskList.get(i);
	        
	        Intent intent = new Intent(recentTaskInfo.baseIntent);
	        if (recentTaskInfo.origActivity != null)
	        	intent.setComponent(recentTaskInfo.origActivity);
	        intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND | 0xFFDFFFFF & intent.getFlags());
	        intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 
	        
	        ResolveInfo resolveInfo = pm.resolveActivity(intent, 65536);
	        if (resolveInfo != null)
	        {
		        SimpleApplicationInfo app = SimpleLauncherModel.getRecentShortcutInfo(resolveInfo);
		        if (app != null){
		        	mRecentApps.add(app);
		        	if (mRecentApps.size() >= RECENT_MAX_DISPLAY_ITEM) // 支持显示8个最近运行的APP
		        		break;
		        }
	        }
	    }
	}
	
	@Override
	protected void onAttachedToWindow(){
		super.onAttachedToWindow();
	}
	
	public void refreshScreen()
	{
		mEmptyResultText.setVisibility(View.GONE);
		mRecentlyUsedGridView.setVisibility(View.GONE);
		mAllAppsGridView.setVisibility(View.GONE);
		mRecentTextView.setVisibility(View.GONE);
		mAllTextView.setVisibility(View.GONE);
		mSearchResultGridView.setVisibility(View.VISIBLE);
		mSearchResultAppsAdapter = new AppsAdapter(mSearchResultApps);
		mSearchResultGridView.setAdapter(mSearchResultAppsAdapter);
		
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mSearchResultGridView.getLayoutParams();
		lp.height = (SimpleUtilities.getValidRows(mSearchResultApps.size()) * mCellHeight);
		lp.width = (4 * mCellWidth);
		mSearchResultGridView.setLayoutParams(lp);
	}

	public void setContext(Context context){
		mContext = context;
	}
	
	public void setSearchWidgetText(CharSequence text)
	{
		if (text != null){
			mSearchWidget.setQuery(text, false);
			mSearchWidget.setIconified(false);
		}
	}

	public void updateAllAppsViewData()
	{
		setContentApps();
		mHandler.post(new Runnable(){
			public void run(){
				updateAllAppsLayout();
			}
		});
	}
	
	public void updateCurrentView(SimpleApplicationInfo appInfo, boolean removed)
	{
		updateRecentApps();
		updateAllApps(appInfo, removed);
	}

	public void updateRecentApps()
	{
		loadRecentApps();
		updateRecentLayout();
	}

	@Override
	public boolean onQueryTextChange(String textChange)
	{
	    if (textChange == null)
	        return true;
	    
	      if ((!TextUtils.isEmpty(textChange)) && (!"".equals(textChange)))
	      {
	    	Locale locale;
	    	SimpleApplicationInfo app;
	    	mSearchResultApps = new ArrayList<SimpleApplicationInfo>();
	      
	        String str;
	        
	        if (mSearchResultApps != null)
	        {
	          mSearchResultApps.clear();
	          locale = Locale.getDefault();
	          str = textChange.toLowerCase(locale);
	          
	          // 在所有App集合中搜索有没有相关标题
	          int allAppsSize = mAllApps.size(); 
	          for (int i = 0; i < allAppsSize; i++){
	        	  app = (SimpleApplicationInfo)mAllApps.get(i);
		          if (app.title != null)
		          {
		        	  String strAppTitle = app.title.toString().toLowerCase(locale);
		        	  if (strAppTitle.indexOf(str) != -1 && mSearchResultApps != null){
		        		  mSearchResultApps.add(app);
		        	  }
		          }
	          }
	        }
	        
			if (mSearchResultApps.size() > 0){
				refreshScreen();
				return true;
			}
	        
	        mRecentlyUsedGridView.setVisibility(View.GONE);
	        mAllAppsGridView.setVisibility(View.GONE);
	        mRecentTextView.setVisibility(View.GONE);
	        mAllTextView.setVisibility(View.GONE);
	        mSearchResultGridView.setVisibility(View.GONE);
	        mEmptyResultText.setVisibility(View.VISIBLE);
	        return true;
	      }
	      
	      if (mSearchResultApps != null){
	        mSearchResultApps.clear();
	        mSearchResultGridView.setVisibility(View.GONE);
	      }
	      
	      if (mRecentApps.size() != 0){
	        mRecentlyUsedGridView.setVisibility(View.VISIBLE);
	        mRecentTextView.setVisibility(View.VISIBLE);
	      }
	      
	      mAllAppsGridView.setVisibility(View.VISIBLE);
	      mAllTextView.setVisibility(View.VISIBLE);
	      mSearchResultGridView.setVisibility(View.GONE);
	      mEmptyResultText.setVisibility(View.GONE);
	      
	      return true;
	}

	@Override
	public boolean onQueryTextSubmit(String str){
		return false;
	}
	
	public class AppsAdapter extends ArrayAdapter<SimpleApplicationInfo>
	{
		private final LayoutInflater mInflater;

		public AppsAdapter(ArrayList<SimpleApplicationInfo> apps){
			super(mContext, 0, apps);
			mInflater = LayoutInflater.from(mContext);
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			SimpleBubbleTextView bubbleTextView;
			if (convertView == null){
				bubbleTextView = (SimpleBubbleTextView)mInflater.inflate(R.layout.simple_activity_application_item, parent, false);
			}else{
				bubbleTextView = (SimpleBubbleTextView)convertView;
			}
			
			SimpleApplicationInfo app = (SimpleApplicationInfo) getItem(position);
			bubbleTextView.applyFolderIconFromBubbleTextView(app, mLauncherApp.getSimpleIconCache());
			bubbleTextView.setOnClickListener((AddApplication)mContext);
			
			return bubbleTextView;
		}
	}

	private class SearchCloseListener implements SearchView.OnCloseListener
	{
		private SearchCloseListener(){
		}

		public boolean onClose()
		{
			if (mRecentApps.size() != 0){
				mRecentlyUsedGridView.setVisibility(View.VISIBLE);
				mRecentTextView.setVisibility(View.VISIBLE);
			}
			
			mAllAppsGridView.setVisibility(View.VISIBLE);
			mAllTextView.setVisibility(View.VISIBLE);
			mSearchResultGridView.setVisibility(View.GONE);
			
			return false;
		}
	}

	public class SearchQueryFocusListener implements View.OnFocusChangeListener{
		public SearchQueryFocusListener(){
		}

		public void onFocusChange(View view, boolean flag){
			View searchBgView = mSearchBg;
			if (flag){
				searchBgView.setVisibility(View.GONE);
			}else{
				searchBgView.setVisibility(View.VISIBLE);
			}
		}
	}

	public class SearchTouchListener implements View.OnTouchListener{
		public SearchTouchListener(){
		}
		
		@Override
		public boolean onTouch(View view, MotionEvent event){
			mSearchWidget.setIconified(false);
			return false;
		}
	}
}
